import java.util.ArrayList;
import java.util.List;

//https://leetcode.cn/problems/pacific-atlantic-water-flow/
class Solution {
    int[] dx = {1, -1, 0, 0};
    int[] dy = {0, 0, 1, -1};
    int m, n;
    public List<List<Integer>> pacificAtlantic(int[][] heights) {
        m = heights.length;
        n = heights[0].length;
        boolean[][] pac = new boolean[m][n];//标记太平洋可流入的位置
        boolean[][] atl = new boolean[m][n];//标记大西洋可流入的位置
        //pac
        for(int j = 0; j < n; j++) dfs(heights, 0, j, pac);
        for(int i = 0; i < m; i++) dfs(heights, i, 0, pac);
        //atl
        for(int j = 0; j < n; j++) dfs(heights, m - 1, j, atl);
        for(int i = 0; i < m; i++) dfs(heights, i, n - 1, atl);

        //都可流入的位置
        List<List<Integer>> ret = new ArrayList<>();
        for(int i = 0; i < m; i++) {
            for(int j = 0; j < n; j++) {
                if(pac[i][j] && atl[i][j]) {
                    List<Integer> list = new ArrayList<>();
                    list.add(i);
                    list.add(j);
                    ret.add(list);
                }
            }
        }
        return ret;
    }
    public void dfs(int[][] heights, int i, int j, boolean[][] check) {
        check[i][j] = true;
        int cur = heights[i][j];
        for(int k = 0; k < 4; k++) {
            int x = i + dx[k];
            int y = j + dy[k];
            if(x >= 0 && x < m && y >= 0 && y < n && check[x][y] == false && heights[x][y] >= cur) {
                dfs(heights, x, y, check);
            }
        }
    }
}